﻿using Abp.Dependency;
using Abp.Domain.Uow;
using Abp.Threading.BackgroundWorkers;
using Abp.Threading.Timers;
using Abp.Domain.Repositories;
using Sunlit.House.Buy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Sunlit.House.Web.Host.Startup
{
    public class MakeGroupOverWorker : PeriodicBackgroundWorkerBase, ISingletonDependency
    {
        private readonly IRepository<GroupBuy, long> _repository;
        public MakeGroupOverWorker(AbpTimer timer,
            IRepository<GroupBuy,long> repository):base(timer)
        {
            _repository = repository;
            Timer.Period = 1000 * 60 * 60 * 1;
        }
        protected override async void DoWork()
        {
            var buys = await _repository.GetAllListAsync(g => g.EndDate.Date == DateTime.Now.Date && g.State == GroupState.OnGoing);

            if (buys.Any())
            {
                foreach (var item in buys)
                {
                    item.State = GroupState.Failed;
                    Logger.Info($"Id为{item.Id}的团购已经过期了！");
                }
            }
            Logger.Debug($"GroupBuy Worker Execute at {DateTime.Now.ToLocalTime()}");
        }
    }
}
